from typing import Dict, Optional
import re
import langdetect

class LanguageDetector:
    """语言检测类，负责识别文本语言类型"""
    def __init__(self):
        self.language_map = {
            'zh': '中文',
            'en': '英文',
            'ja': '日文',
            'ko': '韩文',
            'fr': '法文',
            'de': '德文',
            'es': '西班牙文',
            'ru': '俄文'
        }
        
        # 特殊文本类型的正则表达式
        self.patterns = {
            'code': r'^[\s]*[{\[\(]|^[\s]*(def|class|function|var|let|const|import|from|package)\s',
            'email': r'^[\w\.-]+@[\w\.-]+\.[\w]{2,}$',
            'url': r'^(https?:\/\/)?[\w\.-]+\.[\w]{2,}(\/\S*)?$',
            'number': r'^[+-]?\d*\.?\d+$'
        }
    
    def detect_language(self, text: str) -> Optional[str]:
        """检测文本语言"""
        try:
            lang = langdetect.detect(text)
            # 标准化中文语言代码
            if lang.startswith('zh'):
                return 'zh'
            return lang
        except:
            return None
    
    def detect_content_type(self, text: str) -> str:
        """检测内容类型（代码、邮箱、URL、数字等）"""
        for content_type, pattern in self.patterns.items():
            if re.search(pattern, text.strip()):
                return content_type
        return 'text'
    
    def get_text_info(self, text: str) -> Dict:
        """获取文本的完整信息"""
        lang = self.detect_language(text)
        return {
            'language': lang,
            'language_name': self.language_map.get(lang, '未知语言'),
            'content_type': self.detect_content_type(text),
            'length': len(text),
            'has_chinese': bool(re.search(r'[\u4e00-\u9fff]', text)),
            'has_english': bool(re.search(r'[a-zA-Z]', text)),
            'has_number': bool(re.search(r'\d', text))
        }
    
    def is_mixed_language(self, text: str) -> bool:
        """检测是否为混合语言文本"""
        info = self.get_text_info(text)
        return sum([info['has_chinese'], info['has_english']]) > 1